/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package safemedicalsolution;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import safemedicalsolution.net.RabbitClient;

/**
 *
 * @author Saad
 */
public class FileService implements Runnable {

    private static final Logger log = LoggerFactory.getLogger("Activity.FileService");
    private static final Logger logsms = LoggerFactory.getLogger("Activity.FileService.sms");
    
    private String watchpath;
    private String writePath;
    private int sleepTime = 5000;
    
    private boolean isRunning = false;
    
    private int MAX_SIZE = 1024*1024;
    
    public FileService(String watchpath, String writePath){
        this.watchpath = watchpath;
        this.writePath = writePath;
    }
    
    public void startService(){ 
        isRunning = true;
        Thread t = new Thread(this);
        t.setName("FileWatcher");
        t.start();
    }
    public void stopService(){
        isRunning = false;
    }
    @Override
    public void run() {
        
        try{
            while(isRunning){
                File fs = new File(watchpath);
                File[] files  = fs.listFiles();
                
                for( int i=0; i < files.length; i++){
                    
                    log.info("Read {}", files[i].getName());
                    
                    BufferedReader br = new BufferedReader(new FileReader(files[i].getAbsolutePath()));
                    
                    if ( files[i].length() < MAX_SIZE ){
                    
                        StringBuilder fileData = new StringBuilder();
                    
                        while( true ){                        
                            String line = br.readLine();                        
                            if ( line == null ) break;                                               
                            fileData.append(line);
                        }
                        
                        // add delimeters
                        for( int j=0; j < 80; j++) fileData.append("-");
                        fileData.append("\r\n");
                    
                        br.close();
                                         
                        log.debug("File size={}{}", fileData.length(), "bytes");
                        log.info("Save {}", files[i].getName());

                        logsms.info(fileData.toString());
                    
                        File destdir = new File("fs/processed");
                        Boolean hresult = files[i].renameTo(new File(destdir, files[i].getName()));
                        log.debug("Move {}", hresult.toString());
                    }
                    else 
                    {
                        log.debug("File {} size > {} not allowed", files[i].getName(), MAX_SIZE );
                    }
                }
                
                Thread.sleep(sleepTime);
            }
        }
        catch(Exception ex){
            log.error(ex.getMessage(), ex);
        }
        
    }
    public void writefile(String fileContents)
    {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("HmmssSSS", new Locale("en"));
            String hresult = formatter.format(new Date());
            String uniquefilename = hresult+".txt";
            File newfile = new File(writePath, uniquefilename);
            BufferedWriter fw = new BufferedWriter(new FileWriter(newfile));
            log.debug("Write {}", uniquefilename);
            fw.write(fileContents);
            fw.close();            
        }
        catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    public static void main(String[] args) {
        
        // fs = new FileService("f:\\incomingsms", "");
        //fs.
        RabbitClient rc = new RabbitClient("localhost");
        //rc.initInConnection("Test1");
        //rc.startListening("Test1");
        
        //rc.sendMessage("", "Test1", "Hello World");
       
         /*
       File file = new File("F:/new.txt");
    
       // Destination directory
       File dir = new File("F:/Processed");
    
       // Move file to new directory
       boolean success = file.renameTo(new File(dir, file.getName()));
            if (!success) {
        // File was not successfully moved
            }*/
    }
}
